"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const defines_1 = require("../lib/defines");
function invite(app) {
    const { socket, rooms } = app.locals;
    const { userId } = socket.handshake.query;
    socket.on(defines_1.RequestMethod.invite, function inviteMember(data, cb) {
        const { room, member } = data;
        const { rooms, intercom } = app.locals;
        const __room = rooms[room.classId];
        const __socket = intercom[member.userId];
        if (!__room) {
            return cb && cb({ status: 'error', message: 'room not find!' });
        }
        if (!__socket) {
            return cb && cb({ status: 'error', message: 'member not online!' });
        }
        const mediaOptions = __room.getMediaOption();
        const options = { room: __room.json(), mediaOptions };
        socket.setInviteUser(member);
        try {
            socket.to(__socket.id).timeout(1000 * 60 * 3).emit('invite', options, (error, [data]) => {
                if (error) {
                    if (cb) {
                        cb({ status: 'error', resolve: 'created' });
                    }
                    return;
                }
                socket.emit('invited', { data: member, status: data === null || data === void 0 ? void 0 : data.status });
                socket.broadcast.in(room.classId).emit('invited', { data: member, status: data === null || data === void 0 ? void 0 : data.status });
                if (cb) {
                    cb({ status: 'ok', resolve: 'created' });
                }
            });
        }
        catch (e) {
            console.error(e);
        }
    });
    socket.on(defines_1.RequestMethod.rejectInvite, function dissolve({ room, member }, cb) {
        const __room = rooms[room.classId];
        room = Object.assign(room, __room.json());
        socket
            .timeout(1000 * 2)
            .to(room.classId)
            .emit('rejectInvite', { room, member }, () => {
            __room.getMembers().forEach(member => {
                member.stop(userId);
            });
            if (cb) {
                cb({ status: 'ok', resolve: 'rejectInvite' });
            }
        });
    });
}
exports.default = invite;
